//
//  DetailsOfChargesVC.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/3/3.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "DetailsOfChargesVC.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "DetailsOfChargesCell.h"
#import "DLLApiManager.h"
#import <MJRefresh/MJRefresh.h>
#import "DetailsOfChargesModel.h"
#import "BillingRulesVC.h"
#import "HeaderMacro.h"
#import <QXDataManager/QXDataManager.h>
#import "AppInfoModel.h"
#import "AppManager.h"
#import "AppManagerHeader.h"
@interface DetailsOfChargesVC ()<UITableViewDelegate , UITableViewDataSource>


/**
 总花销
 例如: 100.0元
 */
@property (weak, nonatomic) IBOutlet UILabel *totalFare;


/**
 计价规则
 */
@property (weak, nonatomic) IBOutlet UIButton *valuationRulesButton;

@property (weak, nonatomic) IBOutlet UIButton *cancelButton;

@property (weak, nonatomic) IBOutlet UIImageView *valuationRulesImageView;

@property(nonatomic , strong) NSMutableArray *dataSource;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/// 底部的取消 view
@property (weak, nonatomic) IBOutlet UIView *bottomDismissView;

/// 底部的取消 view 的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomeDismissViewHeight;

/// 底部的取消 button
@property (weak, nonatomic) IBOutlet UIButton *bottomCancelButton;

@property (weak, nonatomic) IBOutlet UIView *footerView;

/// 计价规则背景视图,如果是出租车,这里需要隐藏
@property (weak, nonatomic) IBOutlet UIView *valuationRuleBackView;



@end

@implementation DetailsOfChargesVC
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configureDefaultsAttributes];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if (self.orderSubStatus == OrderStatusEnumCode_PickedUpPasengers_StrokeStart || self.orderSubStatus == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {

            [self getRealTimePriceDetails];
        }else {
            
            [self requestDetailsOfCharges];
        }
        
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}
- (void)configureDefaultsAttributes {
    
    if ([UIScreen mainScreen].bounds.size.width <= 320) {
        
        self.bottomDismissView.hidden = NO;
        self.bottomeDismissViewHeight.constant = 120.0;
        self.cancelButton.hidden = YES;
        self.footerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 100);
        self.tableView.tableFooterView = self.footerView;
        
    }else {
        
        self.bottomDismissView.hidden = YES;
        self.bottomeDismissViewHeight.constant = 0.0;
        self.cancelButton.hidden = NO;
        self.footerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 285);
        self.tableView.tableFooterView = self.footerView;
        
    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[QXDriverConfiguration imageWithName:@"nav_icon_back_white"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction:)];
    
    [self.cancelButton setImage:[QXDriverConfiguration imageWithName:@"public_zhifuxinxi_dacha"] forState:(UIControlStateNormal)];
    
    [self.bottomCancelButton setImage:[QXDriverConfiguration imageWithName:@"public_zhifuxinxi_dacha"] forState:(UIControlStateNormal)];
    
    self.valuationRulesImageView.image = [QXDriverConfiguration imageWithName:@"public_icon_jiajiaguize"];
    
    // 配置默认属性
    self.totalFare.text = [NSString stringWithFormat:@"--元"];
    
    
    AppInfoModel *appModel = [AppManager shareManager].getAppInfo;
    if (appModel.AppDriverType == DriverTypeTaxi) {
        
        self.valuationRuleBackView.hidden = YES;
    }
}

+ (DetailsOfChargesVC *)initDetailsOfChargesVC {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Orders" bundle:[NSBundle mainBundle]];
    DetailsOfChargesVC *detailsOfChargesVC = [storyboard instantiateViewControllerWithIdentifier:@"DetailsOfChargesVCID"];
    
    return detailsOfChargesVC;
}

#pragma mark - 返回按钮
- (void)backAction:(UIBarButtonItem *)barBut {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - cancelAction 取消
- (IBAction)cancelAction:(UIButton *)sender {
    
//    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - valuationRules 计价规则
- (IBAction)valuationRulesAction:(UIButton *)sender {
    
    BillingRulesVC *billingRulesVC = [[BillingRulesVC alloc] init];
    billingRulesVC.title = @"计价规则";
    
    billingRulesVC.urlString = [NSString stringWithFormat:@"%@%@&orderUuid=%@" , [QXDataManager getValueForKey:ZhuJiDriverServiceUrlKey] , [QXDataManager getValueForKey:QXHtml5Kkey_PriceDescription], self.orderUuid];
    [self.navigationController pushViewController:billingRulesVC animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [self dealDetailsOfChargesCellWithTableView:tableView indexPath:indexPath];
    
//    if (self.dataSource.count > 0) {
//        
//        cell = [self dealDetailsOfChargesCellWithTableView:tableView indexPath:indexPath];
//    }
    
    
    
    return cell;
}

- (DetailsOfChargesCell *)dealDetailsOfChargesCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    DetailsOfChargesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailsOfChargesCellID" forIndexPath:indexPath];
    
    if (self.dataSource.count > 0) {
        
        DetailsOfChargesModel *model = self.dataSource[indexPath.row];
        [cell setValueWithDetailsOfChargesModel:model];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}


#pragma mark - 获取费用明细
/**
 获取费用明细
 */
- (void)requestDetailsOfCharges {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.orderUuid forKey:@"orderUuid"];
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverOrderFareDetailsWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            
            [strongSelf.dataSource removeAllObjects];
            
            if (NetWork_Success) {
                
                NSDictionary *dataDic = data[@"data"];
                
                if ([[dataDic allKeys] containsObject:@"totalFare"]) {
                    
                    strongSelf.totalFare.text = [NSString stringWithFormat:@"%.1f元" , [dataDic[@"totalFare"] doubleValue]];
                    
                }else {
                        
                    strongSelf.totalFare.text = [NSString stringWithFormat:@"--元"];
                }
                
                
                if ([[dataDic allKeys] containsObject:@"costItems"]) {
                    
                    NSArray *costItemsArr = dataDic[@"costItems"];
                    if ([costItemsArr isKindOfClass:[NSArray class]]) {
                        
                        if (costItemsArr.count > 0) {
                            
                            for (NSDictionary *costItemsDic in costItemsArr) {
                                
                                DetailsOfChargesModel *model = [DetailsOfChargesModel new];
                                [model setValuesForKeysWithDictionary:costItemsDic];
                                [strongSelf.dataSource addObject:model];
                            }
                        }
                    }
                }
                
            }else {
                    
                strongSelf.totalFare.text = [NSString stringWithFormat:@"--元"];
            }
            
            [strongSelf.tableView reloadData];
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
            [strongSelf.tableView.mj_header endRefreshing];
        });
        
    }];
    
}

#pragma mark - 获取实时价格,如果行程开始,也就是接到乘客
- (void)getRealTimePriceDetails {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.orderUuid forKey:@"orderUuid"];
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverGetRealTimePriceWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            
            [strongSelf.dataSource removeAllObjects];
            
            if (NetWork_Success) {
                
                NSDictionary *dataDic = data[@"data"];
                
                if ([[dataDic allKeys] containsObject:@"totalFare"]) {
                    
                    strongSelf.totalFare.text = [NSString stringWithFormat:@"%.1f元" , [dataDic[@"totalFare"] doubleValue]];
                    
                }else {
                    
                    strongSelf.totalFare.text = [NSString stringWithFormat:@"--元"];
                }
                
                
                if ([[dataDic allKeys] containsObject:@"costItems"]) {
                    
                    NSArray *costItemsArr = dataDic[@"costItems"];
                    if ([costItemsArr isKindOfClass:[NSArray class]]) {
                        
                        if (costItemsArr.count > 0) {
                            
                            for (NSDictionary *costItemsDic in costItemsArr) {
                                
                                DetailsOfChargesModel *model = [DetailsOfChargesModel new];
                                [model setValuesForKeysWithDictionary:costItemsDic];
                                [strongSelf.dataSource addObject:model];
                            }
                        }
                    }
                }
                
            }else {
                
                strongSelf.totalFare.text = [NSString stringWithFormat:@"--元"];
            }
            
            [strongSelf.tableView reloadData];
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
            [strongSelf.tableView.mj_header endRefreshing];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
